
#import <AssertMacros.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <AVFoundation/AVFoundation.h>
#import <CoreFoundation/CoreFoundation.h>
#import <CoreImage/CoreImage.h>
#import <CoreMedia/CoreMedia.h>
#import <ImageIO/ImageIO.h>
#import <libkern/OSAtomic.h>

#import "PYFileManager.h"

#define kDefaultPicturesToCapturePerTap 3
#define kMaxPicturesToCapturePerTap 16
#define kMaxConcurrentBufferOperations 1

typedef void(^pictureProcessingCompleted)(void);
typedef void(^pictureTaken)(CGImageRef);
CMTime sampleBufferDurationCallback(CMBufferRef buffer, void* refcon);
CMBufferQueueRef sampleBufferQueue_;

@protocol PYCaptureSessionManagerDelegate <NSObject>

@optional

-(void)imageRemainingToSaveCountChangedTo:(NSUInteger)count;
// Occurs after all images have been captured, but before we start saving the captured image data
-(void)imageCaptureCompleted;

@end

@interface PYCaptureSessionManager : NSObject
{
    UIDevice *currentDevice;
    AVCaptureSession *session;
    AVCaptureStillImageOutput *stillImageOutput;
    AVCaptureConnection *stillImageConnection;

    CGFloat effectiveScale;
    int32_t imageRemainingToCaptureCount_;
    int32_t imageRemainingToSaveCount_;
    int32_t queueOperationsInProgressCount_;
    
    NSOperationQueue *pictureTakingOperationQueue_;
    ALAssetsLibrary *assetLibrary_;
    pictureTaken picture_taken_delegate_;
}

+(PYCaptureSessionManager*)instance;
-(void)takePicturesWith:(pictureTaken)block;
-(AVCaptureVideoPreviewLayer*)setVideoPreviewView:(UIView*)previewView;

@property (assign) id delegate;
@property (strong) NSMutableArray *images;
@property NSUInteger imageToCaptureCount;

@end

@interface PYCaptureSessionManager (InternalMethods)

-(void)setupAVCapture;
-(void)takePictureWithIndex:(uint32_t)imageIndex;
-(void)imageBufferWasCaptured: (CMSampleBufferRef)imageDataSampleBuffer: (uint32_t)imageIndex: (NSError*)error;
-(void)processBufferQueueWithCompletion:(pictureProcessingCompleted)block;
-(void)processSampleBufferAsCoreGraphics:(CMSampleBufferRef)sampleBuffer withCompletion:(pictureProcessingCompleted)block;
-(void)processSampleBufferAsCocoa:(CMSampleBufferRef)sampleBuffer withCompletion:(pictureProcessingCompleted)block;
-(CGImageRef)newCGImageFromSampleBuffer:(CMSampleBufferRef)sampleBuffer;
-(NSData*)createNSDataFromSampleBuffer:(CMSampleBufferRef)sampleBuffer;
//-(void)didProcessBuffer:(CMSampleBufferRef)buffer;
-(void)saveNSDataImageToCameraRoll:(NSData*)jpegData:(NSDictionary*)attachments withCompletion:(pictureProcessingCompleted)block;
-(void)doneShooting;
-(void)doneProcessingPictures;
-(void)teardownAVCapture;

@end